//
//  SettingLevel2ViewController.m
//  GolfFriend
//
//  Created by Vescky on 14-3-20.
//  Copyright (c) 2014年 vescky.org. All rights reserved.
//

#import "SettingLevel2ViewController.h"
#import "UserSession.h"
#import "UIImageView+MJWebCache.h"
#import "SVProgressHUD.h"
#import "ImageUploader.h"
#import "DXAlertView.h"
#import "AppsEngine.h"

@interface SettingLevel2ViewController ()<UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,ImageUploaderDelegate> {
    UIImagePickerController *photoPicker;
    ImageUploader *imgUploader;
    NSString *oTeamName,*oTeamLogo;
    bool isUploadingPic;
}

@end

@implementation SettingLevel2ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [super customBackButton];
    self.title = @"设置个性签名";
    
    UIButton* publishButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 7, 30, 30)];//
    [publishButton setImage:[UIImage imageNamed:@"btn_sure.png"] forState:UIControlStateNormal];
    [publishButton addTarget:self action:@selector(saveChanges) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* actionItem= [[UIBarButtonItem alloc] initWithCustomView:publishButton];
    [self.navigationItem setRightBarButtonItem:actionItem];
    
    tvMotto.text = [[[UserSession shareUserSession] getUserPublicInfo] objectForKey:@"motto"];
    [tvMotto becomeFirstResponder];
    
    return;
    
    oTeamName = [[UserSession shareUserSession] getTeamName];
    oTeamLogo = [[UserSession shareUserSession] getTeamAvatar];
    
    [tfTeamName setText:oTeamName];
    [imgvTeamLogo setImageURLStr:oTeamLogo placeholder:[UIImage imageNamed:@"default_team_logo.png"]];
    
    imgUploader = [ImageUploader shareImageUploader];
    imgUploader.delegate = self;
    
    isUploadingPic = NO;
}

- (void)saveChanges {
    NSString *userId = [[UserSession shareUserSession] getUserId];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[[UserSession shareUserSession] getUserPublicInfo]];
    [dict setObject:tvMotto.text forKey:@"motto"];
    [[UserSession shareUserSession] savePublicInfo:dict];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:tvMotto.text,@"motto",userId,@"userId",nil];
    [[AppsEngine shareAppsEngine] submitRequest:@"gfModifyUserInfo" param:params onCompletion:^(id jsonResponse) {
        if ([jsonResponse objectForKey:@"status"] && [[jsonResponse objectForKey:@"status"] isEqualToString:@"success"]) {
            [SVProgressHUD showSuccessWithStatus:@"保存成功!"];
            [self goBack];
        }
        else {
            DXAlertView *alertView = [[DXAlertView alloc] initWithTitle:@"温馨提示" contentText:@"保存失败，是否重试?" leftButtonTitle:@"取消" rightButtonTitle:@"重试"];
            alertView.rightBlock = ^(void) {
                [self saveChanges];
            };
            [alertView show];
        }
    } onError:^(NSError *error) {
        DXAlertView *alertView = [[DXAlertView alloc] initWithTitle:@"温馨提示" contentText:@"保存失败，是否重试?" leftButtonTitle:@"取消" rightButtonTitle:@"重试"];
        alertView.rightBlock = ^(void) {
            [self saveModifiedData];
        };
        [alertView show];
    } method:@"GET"];
}

- (void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
    return;
    
    if (isUploadingPic) {
        [SVProgressHUD showErrorWithStatus:@"正在上传图片..."];
        return;
    }
    
    if (![oTeamLogo isEqualToString:[[UserSession shareUserSession] getTeamAvatar]] || ![oTeamName isEqualToString:tfTeamName.text]) {
        //信息已修改，但尚未保存
        DXAlertView *alertView = [[DXAlertView alloc] initWithTitle:@"温馨提示" contentText:@"你更改的信息尚未保存，是否进行保存?" leftButtonTitle:@"取消" rightButtonTitle:@"保存"];
        alertView.rightBlock = ^(void) {
            [self saveModifiedData];
        };
        alertView.leftBlock = ^(void) {
            [self.navigationController popViewControllerAnimated:YES];
        };
        [alertView show];
        return;
    }
    
    [self.navigationController popViewControllerAnimated:YES];
    NSLog(@"over right methor:goBack()");
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSString*)getTeamAvatarSavedName {
    //teamAvatar_[userId]_[sNo].suffix
    NSString *cLink = [NSString stringWithFormat:@"teamAvatar_%@_%@.png",
                       [[UserSession shareUserSession] getUserId],
                       getRandomStrings(5)];
    return cLink;
}

- (void)saveModifiedData {
    oTeamName = tfTeamName.text;
    oTeamLogo = [[UserSession shareUserSession] getTeamAvatar];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:oTeamName,@"teamName",
                                   oTeamLogo,@"teamLogo",nil];
    [[AppsEngine shareAppsEngine] submitRequest:@"gfModifyUserInfo" param:params onCompletion:^(id jsonResponse) {
        if ([jsonResponse objectForKey:@"status"] && [[jsonResponse objectForKey:@"status"] isEqualToString:@"success"]) {
            [SVProgressHUD showErrorWithStatus:@"保存成功!"];
        }
        else {
            DXAlertView *alertView = [[DXAlertView alloc] initWithTitle:@"温馨提示" contentText:@"保存失败，是否重试?" leftButtonTitle:@"取消" rightButtonTitle:@"重试"];
            alertView.rightBlock = ^(void) {
                [self saveModifiedData];
            };
            [alertView show];
        }
    } onError:^(NSError *error) {
        DXAlertView *alertView = [[DXAlertView alloc] initWithTitle:@"温馨提示" contentText:@"保存失败，是否重试?" leftButtonTitle:@"取消" rightButtonTitle:@"重试"];
        alertView.rightBlock = ^(void) {
            [self saveModifiedData];
        };
        [alertView show];
    } method:@"GET"];
}



- (IBAction)btnAction:(id)sender {
    UIButton *btn = (UIButton*)sender;
    if (btn.tag == 101) {
        //更换头像
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机",@"相册", nil];
        [actionSheet showInView:self.view];
    }
    else if (btn.tag == 102) {
        //保存
        [self saveModifiedData];
    }
    
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        //相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIImagePickerController * picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.allowsEditing = YES;  //是否可编辑
            //摄像头
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            photoPicker = picker;
            [self presentModalViewController:photoPicker animated:YES];
        }else{
            //如果没有提示用户
            [SVProgressHUD showErrorWithStatus:@"您的设备不支持拍照!"];
        }
    }
    else if (buttonIndex == 1) {
        //相册
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;  //是否可编辑
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        photoPicker = picker;
        [self presentModalViewController:photoPicker animated:YES];
    }
    NSLog(@"ActionSheel selected:No.%d",buttonIndex);
}


#pragma mark - UINavigationControllerDelegate,UIImagePickerControllerDelegate
//拍摄完成后要执行的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //得到图片
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//[self saveAndResizeImage:image asName:@"tmp.png"]
        dispatch_async(dispatch_get_main_queue(), ^{
            //tb reload
            [imgvTeamLogo setImage:image];
            labelStatus.text = @"正在上传0%";
            labelStatus.hidden = NO;
        });
        NSString *savePath = saveAndResizeImage(image, @"tmp_team_avatar.png",640);
        NSString *serverSavedName = [self getTeamAvatarSavedName];
        [imgUploader uploadImage:savePath asName:serverSavedName];
        [[UserSession shareUserSession] setTeamAvatar:[NSString stringWithFormat:@"%@/%@",Qiniu_Backet_Domain,serverSavedName]];
        isUploadingPic = YES;
    });
    
    //图片存入相册
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    [self dismissModalViewControllerAnimated:YES];
}

//点击Cancel按钮后执行方法
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark - ImageUploaderDelegate
- (void)imageUploaderProcessUpdated:(NSString *)filePath percent:(float)percent {
    labelStatus.text = [NSString stringWithFormat:@"正在上传%.1f%%",percent];
}

//上传完成
- (void)uploadSuccess:(NSString *)filePath ret:(NSDictionary *)ret {
    labelStatus.hidden = YES;
    isUploadingPic = NO;
}


@end
